<template>
  <el-dialog
    v-if="load"
    :close-on-click-modal="false"
    title="关联1688"
    v-model="visible"
    align-center
    width="1200px"
    :z-index="2000"
    @close="handleClose"
  >
    <el-form label-width="80px">
      <el-form-item label="链接类型">
        <el-radio-group v-model="form.goods_link_type">
          <el-radio :label="1">1688链接</el-radio>
          <el-radio :label="2" :disabled="true">非1688链接</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品链接">
        <div class="flex gap-2">
          <el-input v-model="form.goods_link" style="width: 385px"></el-input>
          <el-button link type="primary" :loading="loadings.match" @click="match"
            >匹配1688商品</el-button
          >
        </div>
      </el-form-item>
      <el-form-item label="供应商">
        <VSelect
          v-model="form.supplier_id"
          :options="supplierOptions || []"
          class="w-96"
          disabled
          @change="supplierChange"
          @clear="supplierChange({})"
        />
      </el-form-item>
    </el-form>
    <div>
      <vxe-table :data="data" border>
        <vxe-colgroup title="公司sku信息">
          <vxe-column field="sku" title="sku" width="100"></vxe-column>
          <vxe-column field="sku_specification" title="属性" width="80"></vxe-column>
          <vxe-column title="图片" width="90">
            <template #default="{ row }">
              <VImage :src="row.main_img" width="60" height="60" />
            </template>
          </vxe-column>
          <vxe-column field="sku_cn_title" title="产品名称" width="100">
            <template #default="{ row }">
              <VText :value="row.sku_cn_title" line="3" />
            </template>
          </vxe-column>
          <vxe-column field="price_exclude_tax" title="采购价格" width="100"></vxe-column>
        </vxe-colgroup>
        <vxe-colgroup title="1688关联信息">
          <vxe-column field="subject" title="1688产品名称" width="140">
            <template #default="{ row }">
              <VText :value="row.subject" line="3" />
            </template>
          </vxe-column>
          <vxe-column title="起批量" width="70">
            <template #default="{ row }">
              <VText :value="row.ali_min_order_quantity" />
            </template>
          </vxe-column>
          <vxe-column title="图片" width="90">
            <template #default="{ row }">
              <VImage :src="row.ali_main_image" width="60" height="60" />
            </template>
          </vxe-column>
          <vxe-column title="属性" min-width="120">
            <template #default="{ row }">
              <VSelect
                v-model="row.seclected_sku_info"
                multiple
                collapse-tags
                filterable
                clearable
                :options="
                  (row.ali_sku_info || []).map((d) => ({
                    label: '' + d.attribute_name,
                    value: d.sku_id,
                  }))
                "
                class="w-80"
                @change="({ value }) => selectChange(value, row)"
              />
              <div class="grid grid-cols-7 mt-2 border">
                <div class="border-b p-1 col-span-2">属性</div>
                <div class="border-b p-1 col-span-2">数量</div>
                <div class="border-b p-1 col-span-2">单价</div>
                <div class="border-b p-1"></div>
                <template v-for="(d, i) in row.assoc_sku_info" :key="i">
                  <div class="border-b p-1 flex items-center col-span-2">
                    {{ d.attribute_name }}
                  </div>
                  <div class="border-b p-1 flex items-center col-span-2">
                    <el-input-number
                      v-model="d.sku_num"
                      :controls="false"
                      :min="0"
                      :step="0.01"
                      :precision="0"
                      placeholder="请输入"
                      class="w-full"
                      @change="skuNumChange(d, row)"
                    />
                  </div>
                  <div class="border-b p-1 flex items-center col-span-2">
                    {{ XEUtils.toFixed(d.sku_price, 2) }}
                  </div>
                  <div class="border-b p-1 flex items-center">
                    <el-button
                      link
                      type="primary"
                      @click="
                        row.seclected_sku_info.splice(i, 1) &&
                          selectChange(row.seclected_sku_info, row)
                      "
                      >移除</el-button
                    >
                  </div>
                </template>
              </div>
            </template>
          </vxe-column>
        </vxe-colgroup>
      </vxe-table>
    </div>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit"
        >确 定</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup>
import {
  getSupplierOptions,
  getProductDetail,
  productAssoc,
  productAssocMatch,
} from "./api.js";
import { ElMessage } from "element-plus";
import XEUtils from "xe-utils";
import VImage from "@/components/Image/index.vue";

const load = ref(false);
const visible = ref(false);
const success = ref(false);
let loadings = reactive({});
const form = ref({});
const data = ref([]);
const emit = defineEmits(["close", "success"]);
const supplierOptions = ref([]);
const currentSKU = ref();

watch(
  () => form.value,
  () => {
    data.value = [form.value];
  }
);

// 打开弹窗
const open = async (item) => {
  if (!load.value) {
    load.value = true;
    getSupplierOptions().then((res) => {
      supplierOptions.value = res;
    });
    await 1;
  }
  const r = await getProductDetail({ sku: [item.sku] });
  const res = r.data[0];
  success.value = false;
  form.value = res;
  loadings = reactive({});
  currentSKU.value = item.sku;
  visible.value = true;
};

const clear1688 = () => {
  data.value.forEach((d) => {
    d.ali_main_image = "";
    d.ali_min_order_quantity = "";
    d.subject = "";
    d.ali_sku_info = [];
    d.assoc_sku_info = [];
    d.seclected_sku_info = [];
    return d;
  });
};

// 匹配
const match = () => {
  const { goods_link } = form.value;
  loadings.match = true;
  productAssocMatch({ goods_link, sku: currentSKU.value })
    .then((res) => {
      clear1688();
      form.value = Object.assign({}, form.value, res.data);
      ElMessage.success("匹配成功");
    })
    .finally(() => {
      loadings.match = false;
    });
};
const selectChange = (val, row) => {
  const { ali_price_ranges, assoc_sku_info, ali_sku_info } = row;
  row.assoc_sku_info = row.assoc_sku_info.filter((d) => val.includes(d.sku_id));
  val.forEach((v) => {
    if (assoc_sku_info.some((d) => d.sku_id === v)) return;
    const item = {
      ...(ali_sku_info.find((d) => d.sku_id === v) || {}),
      sku_num: row.ali_min_order_quantity,
    };
    if (ali_price_ranges.length > 1) {
      item.sku_price = ali_price_ranges[0]?.price;
    }
    row.assoc_sku_info.push(item);
  });
};

const skuNumChange = (item, row) => {
  const { ali_price_ranges } = row;
  if (ali_price_ranges.length < 2) {
    return;
  }
  const allNum = row.assoc_sku_info.reduce((acc, cur) => (acc += +cur.sku_num || 0), 0);
  const { price } = ali_price_ranges.findLast((d) => allNum >= d.startQuantity) ||
    ali_price_ranges[0] || { price: 0 };
  row.assoc_sku_info.forEach((d) => {
    d.sku_price = price;
  });
};

const supplierChange = ({ option }) => {
  if (option) {
    form.value.supplier_name = option.label;
  }
  clear1688();
};

// 关闭弹窗
const close = () => {
  visible.value = false;
};

const handleClose = () => {
  emit("close");
};
// 提交
const submit = () => {
  loadings.submit = true;
  const item = data.value[0];
  // item.p_id = form.value.p_id
  productAssoc(item)
    .then((res) => {
      success.value = true;
      emit("success", item);
      ElMessage.success("操作成功");
      close();
    })
    .finally(() => {
      loadings.submit = false;
    });
};

defineExpose({ open });
</script>
